package com.bit.demo16;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class EchoServer {
    private DatagramSocket socket;
    public EchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println();
        System.out.println("server start!");
        while(true){
            // 1. 读取请求并解析
            //  1) 创建一个空白的 DatagramPacket 对象
            DatagramPacket rePacket=new DatagramPacket(new byte[4090],4090);
            //  2) 通过 receive 读取网卡的数据. 如果网卡没有收到数据, 就会阻塞等待.
            socket.receive(rePacket);
            //  3) 把 DatagramPacket 中的数据解析成字符串. 只需要从 DatagramPacket 取到有效的数据即可.
            String request=new String(rePacket.getData(),0,rePacket.getLength());
            // 2. 根据请求计算响应
            String response=process(request);
            // 3. 把响应写回到客户端
            //  1) 把响应构造成 DatagramPacket 对象
            DatagramPacket respPacket=new DatagramPacket(response.getBytes(),response.getBytes().length,rePacket.getSocketAddress());
            //  2) 把 DatagramPacket 写回到客户端.
            socket.send(respPacket);
            // 4. 打印日志.
            System.out.printf("[%s:%d] req: %s, resp: %s\n",
                    rePacket.getAddress(), rePacket.getPort(), request, response);
        }
    }
    public String process(String request) {
        return "接收到请求"+request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer server=new EchoServer(9090);
        server.start();
    }
}
